﻿using CQRSFramework.Common.Serializer;
using CQRSFramework.Events;
using CQRSFramework.Infrustructures;
using CQRSFramework.Messages;
using System.Collections.Generic;

namespace CQRSFramework.RabbitMQ.Impl
{
    public class DomainEventPublisher : IDomainEventPublisher
    {
        private readonly ITypeNameProvider _typeNameProvider;
        private readonly IJsonSerializer _jsonSerializer;
        private readonly IMessagePublisher _messagePublisher;
        private readonly IRoutingKeyProvider<IDomainEvent> _routingKeyProvider;
        public DomainEventPublisher(ITypeNameProvider typeNameProvider, IJsonSerializer jsonSerializer, IMessagePublisher messagePublisher, IRoutingKeyProvider<IDomainEvent> routingKeyProvider)
        {
            _typeNameProvider = typeNameProvider;
            _jsonSerializer = jsonSerializer;
            _messagePublisher = messagePublisher;
            _routingKeyProvider = routingKeyProvider;
        }
        public void Publish(IEnumerable<IDomainEvent> domainEvents)
        {
            foreach (var message in domainEvents)
            {
                _messagePublisher.Publish(BuildMessage(message), "", _routingKeyProvider.GetRoutingKey(message));
            }
        }
        private QueueMessage BuildMessage(IDomainEvent evnt)
        {
            var queueMessage = new QueueMessage
            {
                TypeName = _typeNameProvider.GetTypeName(evnt.GetType()),
                Body = _jsonSerializer.Serialize(evnt)
            };
            return queueMessage;
        }
    }
}
